package ToolClass;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.ObjectMetadata;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;

/**
 * 阿里云OSS客户端
 *
 * @quther lianghao
 * @Date 2020/12/26
 */
public class OssAliClientClass {
    /**
     * 用户的存储空间所在数据中心的访问域名
     *  oss-cn-beijing.aliyuncs.com
     *  oss-cn-hangzhou.aliyuncs.com
     *  oss-cn-shanghai.aliyuncs.com
     *  oss-cn-qingdao.aliyuncs.com
     *  oss-cn-zhangjiakou.aliyuncs.com
     *  oss-cn-shenzhen.aliyuncs.com
     *  oss-cn-guangzhou.aliyuncs.com
     *  oss-cn-chengdu.aliyuncs.com
     *  oss-cn-hongkong.aliyuncs.com
     *  oss-ap-southeast-1.aliyuncs.com
     */
    private static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    /**开发环境**/
//    static final String ACCESS_KEY_ID = "LTAIx3ENCnFcePg8";
//    static final String ACCESS_KEY_SECRET = "F8yDZJhAxHPPxHunta8i5x6tGbbVt0";
//    static final String BUCKET_NAME = "mytestbucket007";
    /**生产环境**/
    static final String ACCESS_KEY_ID = "LTAI4G2kV8sQE7o4DXzfapRN";
    static final String ACCESS_KEY_SECRET = "tfdjqWBFWxj7tgdgRUFCAmU912998F";
    static final String BUCKET_NAME = "kongxing";
    private static OSS ossClient;

    /**
     * @desc 静态初始化ossClient
     **/
    static {
        ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }
    /**
     * @desc 上传本地文件（文件流上传）
     **/
    public static String uploadFile(InputStream is, String directory, String fileName) {
        String key =  directory + File.separator + fileName;
        if (directory == null || directory.isEmpty()) {
            key = fileName;
        }
        try {
            ObjectMetadata objectMetadata = getObjectMetadata(is.available(),fileName);
            ossClient.putObject(BUCKET_NAME, key, is, objectMetadata);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            IOUtils.safeClose(is);
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return  key;
    }
    private static ObjectMetadata getObjectMetadata(long length,String fileName) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(length);
        // 被下载时网页的缓存行为
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        // 指定上传文件操作时是否覆盖同名Object。
        // 不指定x-oss-forbid-overwrite时，默认覆盖同名Object。
        // 指定x-oss-forbid-overwrite为false时，表示允许覆盖同名Object。
        // 指定x-oss-forbid-overwrite为true时，表示禁止覆盖同名Object，如果同名Object已存在，程序将报错。
        objectMetadata.setHeader("x-oss-forbid-overwrite", "false");
        return objectMetadata;
    }


    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if ("bmp".equalsIgnoreCase(FilenameExtension)) {
            return "image/bmp";
        }
        if ("gif".equalsIgnoreCase(FilenameExtension)) {
            return "image/gif";
        }
        if ("jpeg".equalsIgnoreCase(FilenameExtension) ||
                "jpg".equalsIgnoreCase(FilenameExtension) ||
                "png".equalsIgnoreCase(FilenameExtension)) {
            return "image/jpeg";
        }
        if ("html".equalsIgnoreCase(FilenameExtension)) {
            return "text/html";
        }
        if ("txt".equalsIgnoreCase(FilenameExtension)) {
            return "text/plain";
        }
        if ("vsd".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.visio";
        }
        if ("pptx".equalsIgnoreCase(FilenameExtension) ||
                "ppt".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if ("docx".equalsIgnoreCase(FilenameExtension) ||
                "doc".equalsIgnoreCase(FilenameExtension)) {
            return "application/msword";
        }
        if ("xml".equalsIgnoreCase(FilenameExtension)) {
            return "text/xml";
        }
        return "image/jpeg";
    }
    /**
     * @desc 上传网络图片
     **/
    public static String uploadWebFile(String fileUrl, String directory, String fileName) {
        String key =  directory + "/" + fileName;
        InputStream is = null;
        try {
            Integer length = new URL(fileUrl).openConnection().getContentLength();
            is = new URL(fileUrl).openStream();
            ObjectMetadata objectMetadata = getObjectMetadata(length,fileName);
            ossClient.putObject(BUCKET_NAME, key, is, objectMetadata);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            IOUtils.safeClose(is);
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return  key;
    }

    /**
     * 删除文件
     * @param bucketName
     * @param objectName
     */
    public static void delete(String bucketName, String objectName){
        try {
            // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
            ossClient.deleteObject(bucketName, objectName);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 关闭OSSClient。
            if(ossClient!=null){
                ossClient.shutdown();
            }
        }

    }



    public static void main(String [] args){
        String path = "D:\\Temp\\head5.jpg";
        InputStream in = null;
        try {
            in =new FileInputStream(new File(path));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        uploadFile(in,"head","head5.jpg");

    }

}
